package org.feng.manager;

import jakarta.annotation.Resource;
import org.feng.entity.Columns;
import org.feng.entity.Tables;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 数据库信息结构管理器
 *
 * @author mcp
 * @version 1.0
 * @since 2025-05-07 11:27
 */

@SuppressWarnings("all")
@Component
public class InformationSchemaManager {

    @Resource
    private JdbcTemplate jdbcTemplate;

    /**
     * 查找所有可用的的表名
     */
    public List<Tables> findAllTableNames(String tableSchema) {
        String sql = "SELECT TABLE_NAME,TABLE_COMMENT FROM information_schema.TABLES WHERE TABLE_SCHEMA = ?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Tables.class), tableSchema);
    }

    /**
     * 查找所有可用的列名
     */
    public List<Columns> findAllColumns(String tableSchema, String tableName) {
        String sql = "SELECT COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = ?";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Columns.class), tableSchema, tableName);
    }


    /**
     * 查找所有可用的schema名
     */
    public List<String> findAllSchemaNames() {
        String sql = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA";
        return jdbcTemplate.queryForList(sql, String.class);
    }

    /**
     * 查找表创建语句
     */
    public Map<String, Object> getCreateTableStatement(String tableSchema, String tableName) {
        String sql = "SHOW CREATE TABLE `" + tableSchema + "`.`" + tableName + "`";
        return jdbcTemplate.queryForMap(sql);
    }
}


